package com.jiyinit.web.core.business.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.AESUtil;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.core.framework.base.util.MD5Util;
import com.jiyinit.core.framework.dao.mybatis.paginator.domain.PageBounds;
import com.jiyinit.web.core.business.dto.OrgPageRequest;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.UserRoleServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.business.vo.UserRoleVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.PinyinUtil;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.List;

/**
 * 用户管理
 *
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

    @Resource(name = "core.userRoleServiceImpl")
    private UserRoleServiceImpl userRoleService;


    /**
     * 跳转到查询用户信息页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/toFindUserList")
    public String toFindUserList(HttpServletRequest request) {
        return "/user/userList";
    }

    /**
     * 按条件查询用户信息
     *
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/findByPage")
    public PagingResult findByPage(HttpServletRequest request, UserRequest userRequest) {
        userRequest.setLimit(10);
        PagingResult pagingResult = userService.getUserInfoListByCondiction(userRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }

    /**
     * 跳到新增页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request) {
        return "/user/add";
    }

    /**
     * 新增用户
     *
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public ResponseEntity<ResponseDto> save(HttpServletRequest request, UserRequest userRequest) {
        // 校验参数
        ValidateResult<UserRequest> validateResult = paramCheckLogic.checkParamValidate(userRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreUserEntity coreUser = new TabCoreUserEntity();
        BeanUtils.copyProperties(userRequest, coreUser);
        String password = MD5Util.MD5Encode(userRequest.getPassword());
        //显示顺序
        if(userRequest.getInOrder()==null){
            //根据部门查询人员的最后顺序
            Integer inOrder = userService.selectMaxOrder(userRequest.getOrgId());
            coreUser.setInOrder(new Integer(inOrder.intValue()+1));
        }
        coreUser.setPassword(password);
        coreUser.setCreateTime(new Date());
        coreUser.setCreateId(UserUtil.getCurrentUser().getUserId());
        coreUser.setLastModifyTime(new Date());
        coreUser.setLastModifyId(UserUtil.getCurrentUser().getUserId());
        coreUser.setUserStatus(new Integer(1));
        coreUser.setIsDelete(new Integer(0));
        coreUser.setHeadChar(PinyinUtil.trans2HeadChar(userRequest.getUserName()));
        coreUser.setFullName(PinyinUtil.trans2QuanPin(userRequest.getUserName()));
        //初始化工资表秘钥和进入工资表功能的二次密码
        int a=(int) (Math.random()*89999999+10000000);
        String s= String.valueOf(a);
        String salarySecretKey= AESUtil.encrypt(s);
        coreUser.setSalarySecretKey(salarySecretKey);
        String salaryPassword = AESUtil.encrypt("12345678");
        coreUser.setSalaryPassword(salaryPassword);

        int num = userService.insert(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 跳到修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Model model,HttpServletRequest request,Integer userId) {
        LogUtil.info(LOGGER, "userId:{}", userId);
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userId);
        TabCoreOrgEntity coreOrg = orgService.selectById(coreUser.getOrgId());
        UserRoleVo userRoleVo = userRoleService.selectUserRoleVoByUserId(coreUser.getUserId());
        model.addAttribute("user",coreUser);
        model.addAttribute("org",coreOrg);
        model.addAttribute("userRole",userRoleVo);
        return "/user/edit";
    }

    /**
     * 修改用户信息
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/modify")
    public ResponseEntity<ResponseDto> modify(HttpServletRequest request, UserRequest userRequest) {
        // 校验参数
        ValidateResult<UserRequest> validateResult = paramCheckLogic.checkParamValidate(userRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userRequest.getUserId());
        BeanUtils.copyProperties(userRequest, coreUser);

        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        coreUser.setLastModifyId(currentUser.getUserId());
        coreUser.setLastModifyTime(new Date());
        coreUser.setHeadChar(PinyinUtil.trans2HeadChar(coreUser.getUserName()));
        coreUser.setFullName(PinyinUtil.trans2QuanPin(coreUser.getUserName()));

        int num = userService.updateUserInfoById(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 删除用户信息
     * @param request
     * @param userIds
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/delete")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request,Integer[] userIds) {
        LogUtil.info(LOGGER, "userIds:{}", userIds);
        int num = userService.deleteUserLogicByIds(userIds);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 检查用户登录名是否重否
     * @param request
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/check")
    public ResponseEntity<ResponseDto> check(HttpServletRequest request,String loginName) {
        LogUtil.info(LOGGER, "loginName:{}", loginName);
        TabCoreUserEntity coreUser = userService.getUserInfoByLoginName(loginName);
        if(coreUser == null){
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 跳转到密码修改界面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toModifyPassword")
    public String toModifyPassword(Model model,HttpServletRequest request,Integer userId) {
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userId);
        model.addAttribute("user",coreUser);
        return "/user/modifyPassword";
    }




    /**
     * 修改密码
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/modifyPassword")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request,UserRequest userRequest) {
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userRequest.getUserId());
        String password = MD5Util.MD5Encode(userRequest.getPassword());
        coreUser.setPassword(password);
        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        coreUser.setLastModifyId(currentUser.getUserId());
        coreUser.setLastModifyTime(new Date());
        int num = userService.updateUserInfoById(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 跳转到密码修改界面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toModifySalaryPassword")
    public String toModifySalaryPassword(Model model,HttpServletRequest request,Integer userId) {
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userId);
        model.addAttribute("user",coreUser);
        return "/user/modifySalaryPassword";
    }

    /**
     * 修改工资条密码
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/modifySalaryPassword")
    public ResponseEntity<ResponseDto> modifySalaryPassword(HttpServletRequest request,UserRequest userRequest) {
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userRequest.getUserId());
        String salaryPassword = AESUtil.encrypt(userRequest.getSalaryPassword());
        coreUser.setSalaryPassword(salaryPassword);
        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        coreUser.setLastModifyId(currentUser.getUserId());
        coreUser.setLastModifyTime(new Date());
        int num = userService.updateUserInfoById(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 
         * 按机构查询用户
         * @author wuyuefeng
         * @create 2017年4月27日 下午2:09:18
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/anon/findUsersByOrId")
    public PagingResult findUsersByOrId(HttpServletRequest request,UserRequest userRequest) {
        LogUtil.info(LOGGER, "orgId:{}", userRequest.getOrgId());
        userRequest.setLimit(10);
        PagingResult pagingResult = userService.findUsersByOrId(userRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }

    /**
     * 初始化姓名的拼音，首字母
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/initialization")
    public ResponseEntity<ResponseDto> init(HttpServletRequest request) {
        Integer count = userService.findCount();
        Integer batch = (count + 100 -1)/100;

        for (int i =1;i<= batch;i++){
        PageBounds pageBounds = new PageBounds();
        pageBounds.setLimit(100);
        pageBounds.setPage(i);
        PagingResult pagingResult = userService.findUsers(pageBounds);
            List<TabCoreUserEntity>  users = pagingResult.getRows();
            for (TabCoreUserEntity u: users){
                if(u.getUserName() != null && !"".equals(u.getUserName())){
                    u.setFullName(PinyinUtil.trans2QuanPin(u.getUserName()));
                    u.setHeadChar(PinyinUtil.trans2HeadChar(u.getUserName()));
                }
            }
            if(users != null) userService.updatePinyin(users);
        }

        return  new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
    }

}
